<?php namespace nimo\domains\acc\controllers;

use BaseController;
use Input;
use View;
use Validator;
use Redirect;
use Request;
use Response;


use nimo\common\csv\Importer;
use nimo\common\csv\Exporter;
use nimo\common\csv\SimpleInterceptor;
use nimo\common\csv\DatabaseInterceptor;
use nimo\common\csv\CsvConverter;
use nimo\common\design\PComposite;
use nimo\common\design\IVisitor;
use nimo\domains\acc\batch\csv\MasterCodeCsvImportConverter;

class MasterCodeBatchController extends BaseController {


    public function __construct() {
    }

    public function import()
    {
        if(!Request::isMethod('POST')) {
            return View::make('nimo.domains.acc.master.code.import');
        }
        //$input = Input::all();
        //$rules = array(
        //    'files' => 'image|max:3000',
        //);
        //$validation = Validator::make($input, $rules);
        //if ($validation->fails()) {
        //    return Response::make($validation->errors->first(), 400);
        //}
        
        /*
        $file = __DIR__.'/../batch/edinet_account.csv';
	$configs = array();
	$converter = new EdinetAccountConverter();
	$batch = new PrimitiveAccountBatch($file, $configs, $converter);
	$batch->import();
	*/

        
        $file = Input::file('files');
        if (!$file->isValid()) {
            //return json_encode(array('status' => 'NG', ));
            return Response::json(array('message'=>$file->getError()), 400);
        }
        
        
        //read file & keep data in si
        $si = new SimpleInterceptor();
        $configs = array('fromCharset' => 'Shift-JIS');
        $ci = new Importer($file->getRealPath(), $configs, $si);
        $ci->execute();
        
        $lines = $si->getDatas();
        
        // create composite model
        $converter = new MasterCodeCsvImportConverter();
        $roots = PComposite::makeTreeByDepth($lines, $converter);

        
        return json_encode(array(
            'filename' => $file->getClientOriginalName(),
            'msize' => $file-> getMaxFilesize(),
            'data'  => $roots,
            'status' => 'OK'
        ));
    }

    public function import2()
    {
        $codeM = Input::get('codeM');
        $codeS = Input::get('codeS');
        
        if ($codeS) {
          $accounts = Account::where('code', '=', $codeM)->get();
        } else {
          $accounts = Account::where('code', 'like', $codeM.'%')->get();
        }
        if (Request::ajax()) {
            return Response::json($accounts);
        }
        $jsonAccount = json_encode($accounts);
        return View::make('nimo.domains.master.account.index', compact('accounts', 'jsonAccount'));
    }
}